# -*- coding: utf-8 -*-

# @File  : _db.py
# @Author: Lomo
# @Site  : lomo.space
# @Date  : 2019-12-01
# @Desc  : DML


import pymysql

from config.db_config import DB_CONFIG


class _DB(object):
    def __init__(self, host, port, user, password, database):
        self.host = DB_CONFIG.get('host') if host is None else host
        self.port = DB_CONFIG.get('port') if port is None else port
        self.user = DB_CONFIG.get('user') if user is None else user
        self.password = DB_CONFIG.get('password') if password is None else password
        self.db = DB_CONFIG.get('database') if database is None else database

        self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user,
                                    password=self.password, db=self.db)
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def __enter__(self):
        return self.cur

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.conn.commit()
        self.cur.close()
        self.conn.close()


# 测试
if __name__ == '__main__':
    with _DB(host='localhost', port=3306, user='root', password='lomo16888', database='api_doc') as db:
        db.execute("select * from users")
        print(db)
        for i in db:
            print(i)  # 查出每条数据
            print(i['username'])  # lomo123456
